package com.s69.demo.service;

import com.s69.demo.dao.BackendUserDao;
import com.s69.demo.dao.DevUserDao;
import com.s69.demo.dto.LoginDto;
import com.s69.demo.entity.BackendUser;
import com.s69.demo.entity.DevUser;
import com.s69.demo.utils.SessionUtils;
import com.s69.demo.utils.SysConstant;
import com.s69.demo.utils.TokenUtils;
import com.s69.demo.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginService {

    @Autowired
    BackendUserDao backendUserDao;
    @Autowired
    DevUserDao devUserDao;

    public LoginDto login(LoginDto loginDto) {
        LoginVo loginVo = new LoginVo();
        if (loginDto.getUserType() == SysConstant.UserTypeInt.admin) {
            BackendUser backendUser = new BackendUser();
            backendUser.setUsercode(loginDto.getAccount());
            backendUser.setUserpassword(loginDto.getPassword());
            List<BackendUser> list = backendUserDao.queryAllBy(backendUser);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("账号或密码错误");
            }
            String token = TokenUtils.createToken(list.get(0).getId() + "", list.get(0).getUsercode(), SysConstant.UserTypeStr.admin);
            SessionUtils.put(token, list.get(0));
            loginDto.setToken(token);
//            loginVo.setToken(token);
            return loginDto;
        } else if (loginDto.getUserType() == SysConstant.UserTypeInt.dev) {
            DevUser devUser = new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());
            List<DevUser> list = devUserDao.queryAllBy(devUser);
            if (list == null || list.size() == 0) {
                throw new RuntimeException("账号或密码错误");
            }
            String token = TokenUtils.createToken(list.get(0).getId() + "", list.get(0).getDevcode(), SysConstant.UserTypeStr.dev);
            SessionUtils.put(token, list.get(0));
            loginDto.setToken(token);
//            loginVo.setToken(token);
            return loginDto;
        } else {
            throw new RuntimeException("没有该用户类型");
        }
    }
}
